public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode A = headA, B = headB;
        while (A != B) {
            A = A != null ? A.next : headB;
            B = B != null ? B.next : headA;
        }
        return A; // 如果有交点，返回交点；如果没有交点，返回 null
    }

    // ListNode 类定义
    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    // 辅助方法：创建链表
    public static ListNode createLinkedList(int[] values) {
        ListNode dummy = new ListNode(0);
        ListNode current = dummy;
        for (int value : values) {
            current.next = new ListNode(value);
            current = current.next;
        }
        return dummy.next;
    }

    // 辅助方法：打印链表
    public static void printList(ListNode head) {
        while (head != null) {
            System.out.print(head.val + " -> ");
            head = head.next;
        }
        System.out.println("null");
    }

    public static void main(String[] args) {
        Solution solution = new Solution();

        ListNode headA = createLinkedList(new int[]{1, 2, 3});
        ListNode headB = createLinkedList(new int[]{4, 5});
        ListNode intersection = createLinkedList(new int[]{6, 7});
        headA.next.next.next = intersection; // 1 -> 2 -> 3 -> 6 -> 7
        headB.next.next = intersection;      // 4 -> 5 -> 6 -> 7

        System.out.println("Intersection Node Value: " + solution.getIntersectionNode(headA, headB).val);
    }
}